<template>
  <a-spin :spinning="spinning">
    <a-card title="基础信息">
      <a-form :form="form">
        <a-row :gutter="10">
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="工号" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input placeholder="请输入工号" :disabled="readOnly" v-decorator="[
                'uuid',
                { rules: [{ required: true, message: '请输入工号' }] },
              ]" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="账号" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input placeholder="请输入账号" :disabled="readOnly" v-decorator="[
                'account',
                { rules: [{ required: true, message: '请输入账号' }] },
              ]" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="密码" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input-password placeholder="请输入密码" :disabled="
                this.modifyEntity.operation != this.operationFlag.Add
              " v-decorator="[
  'pwd',
  { rules: [{ required: true, message: '请输入密码' }] },
]" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="10">
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="昵称" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input placeholder="请输入昵称" :disabled="readOnly" v-decorator="[
                'nickName',
                { rules: [{ required: true, message: '请输入昵称' }] },
              ]" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="出生年月" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-date-picker placeholder="请输入出生年月" :disabled="readOnly" v-decorator="['birthday']"
                style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="性别" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-switch :disabled="readOnly" v-decorator="[
                'gender',
                { valuePropName: 'checked', initialValue: true },
              ]" un-checked-children="女" checked-children="男" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="10">
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="籍贯" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-tree-select :disabled="readOnly" :tree-data="nationalitys" tree-default-expand-all
                v-decorator="['nationality']" @change="handleNationalityChange" placeholder="请选择籍贯" style="width: 100%">
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="毕业院校" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-select :disabled="readOnly" v-decorator="['education']" @change="handleEducationChange"
                placeholder="请选择毕业院校" style="width: 100%">
                <a-select-option v-for="item in educations" :key="item.id" :value="item.id">{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="学位" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-select :disabled="readOnly" v-decorator="['academicDegree']" @change="handleAcademicDegreeChange"
                placeholder="请选择学位" style="width: 100%">
                <a-select-option v-for="item in academicDegrees" :key="item.id" :value="item.id">{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="10">
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="邮箱" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input placeholder="请输入邮箱" :disabled="readOnly" v-decorator="['email']" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="手机电话" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input placeholder="请输入手机电话" :disabled="readOnly" v-decorator="['mobilePhone']" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="办公电话" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input placeholder="请输入办公电话" :disabled="readOnly" v-decorator="['officePhone']" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="10">
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="头像" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-upload list-type="picture-card" :file-list="fileList" :before-upload="beforeUpload"
                :transform-file="transformFile" @preview="handlePreview" @change="handleImgChange">
                <div v-if="fileList.length < 1">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">上传LOGO</div>
                </div>
              </a-upload>
              <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                <img alt="" style="width: 100%" :src="previewImage" />
              </a-modal>
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="投放开关" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-switch :disabled="readOnly" v-decorator="[
                'isPush',
                { valuePropName: 'checked', initialValue: true },
              ]" un-checked-children="关闭" checked-children="开启" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card title="详细信息" class="element-top">
      <a-form :form="form">
        <a-row :gutter="10">
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="用户类型" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-select :disabled="readOnly" v-decorator="[
                'userType',
                { rules: [{ required: true, message: '请选择用户类型' }] },
              ]" placeholder="请选择用户类型" style="width: 100%">
                <a-select-option :key="item.val" :value="item.val" v-for="(item) in userTypeList">{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="所属部门" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-tree-select tree-data-simple-mode tree-default-expand-all placeholder="请选择所属部门" :disabled="readOnly"
                v-decorator="[
                  'defaultOrganizeId',
                  { rules: [{ required: true, message: '请选择所属部门' }] },
                ]" :treeData="orgs" @change="handleOrgChange"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"></a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="所属岗位" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-select :disabled="readOnly" v-decorator="[
                'defaultPostationId',
                { rules: [{ required: true, message: '请选择所属岗位' }] },
              ]" @change="handlePositionChange" placeholder="请选择所属岗位" style="width: 100%">
                <a-select-option v-for="item in positions" :key="item.id" :value="item.id">{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="所属角色" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-select :disabled="readOnly" v-decorator="[
                'roleId',
                { rules: [{ required: true, message: '请选择所属角色' }] },
              ]" @change="handleRoleChange" placeholder="请选择所属角色" style="width: 100%">
                <a-select-option v-for="item in roles" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="是否删除" :labelCol="labelCol" :wrapperCol="wrapperCol" required>
              <a-switch :disabled="readOnly" v-decorator="[
                'deleteFlag',
                { valuePropName: 'checked', initialValue: false },
              ]" un-checked-children="否" checked-children="是" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="状态" :label-col="labelCol" :wrapperCol="wrapperCol">
              <a-switch :disabled="readOnly" v-decorator="[
                'status',
                { valuePropName: 'checked', initialValue: true },
              ]" un-checked-children="冻结" checked-children="正常" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="10">
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="简介" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-textarea :disabled="readOnly" v-decorator="['description']" placeholder="请输入简介" :rows="4" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card v-if="readOnly" class="element-top" title="其他信息">
      <a-form :form="form">
        <a-row>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="当前登录时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :disabled="readOnly" v-decorator="['currentLoginTime']" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="登录总次数" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :disabled="readOnly" v-decorator="['loginTotalCount']" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="上次登录时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :disabled="readOnly" v-decorator="['lastLoginTime']" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="上次登录IP地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :disabled="readOnly" v-decorator="['lastLoginIp']" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="创建时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :disabled="readOnly" v-decorator="['createTime']" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="创建人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :disabled="readOnly" v-decorator="['createUser']" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="修改时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :disabled="readOnly" v-decorator="['updateTime']" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" :xxl="8">
            <a-form-item label="修改人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :disabled="readOnly" v-decorator="['updateUser']" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <footer-tool-bar>
      <a-space>
        <a-button icon="rollback" @click="handleRefresh">返回</a-button>
        <a-button icon="reload" v-if="!readOnly" @click="handleReset" :loading="loading">重置</a-button>
        <a-button icon="check-circle" v-if="!readOnly" :loading="loading" @click="handleSubmit">保存</a-button>
      </a-space>
    </footer-tool-bar>
  </a-spin>
</template>

<script>
// MD5加密
import md5 from "md5";
import footerToolBar from "@/components/footerToolbar";
import { queryDicSelect, queryDicTreeSelect } from "@/views/sysModule/system/dic/dic";
import { queryOrgTreeSelect } from "@/api/sys/identity/org";
import { queryPositionSelect } from "@/api/sys/identity/position";
import { queryRoleSelect } from "@/api/sys/permission/role";
import {
  getAdminUser,
  addAdminUser,
  updateAdminUser,
} from "@/api/sys/identity/adminUser";
import { getBase64 } from "@/utils/convertUtils/convert";
export default {
  components: {
    footerToolBar,
  },
  props: {
    modifyEntity: {
      type: Object,
      required: true,
      default: function () {
        return {
          // 传递的主键
          id: "",
          // 页面标题
          title: "新增平台员工",
          // 页面操作类型
          operation: this.operationFlag.Add,
          // 是否展示编辑页面
          showModify: false,
        };
      },
    },
  },
  data() {
    return {
      userTypeList: [{ val: 1, name: '系统管理' }, { val: 2, name: '系统业务' }, { val: 3, name: '乙方机构' }, { val: 4, name: '渠道商' }],
      // 显示描述宽度
      labelCol: { md: { span: 8 }, xs: { span: 24 }, sm: { span: 12 } },
      // 输入框宽度
      wrapperCol: { md: { span: 16 }, xs: { span: 24 }, sm: { span: 12 } },
      // 执行保存后是否关闭当前页面
      hasClose: false,
      // 遮罩层加载
      spinning: false,
      // 按钮加载状态
      loading: false,
      // 只读状态
      readOnly: false,
      form: this.$form.createForm(this),
      entity: {},
      orgs: [],
      roles: [],
      positions: [],
      nationalitys: [],
      academicDegrees: [],
      educations: [],
      // 图片上传
      imgloading: false,
      previewVisible: false,
      previewImage: "",
      fileList: [],
    };
  },
  mounted() {
    // 毕业院校
    queryDicSelect({ dicTypeUniqueCode: "Education" }).then((res) => {
      this.educations = res.data;
    });
    // 学历
    queryDicSelect({ dicTypeUniqueCode: "AcademicDegree" }).then((res) => {
      this.academicDegrees = res.data;
    });
    // 籍贯
    queryDicTreeSelect({ dicTypeUniqueCode: "Aationality" }).then((res) => {
      this.nationalitys = res.data;
    });
    queryOrgTreeSelect({ dimDefault: true }).then((res) => {
      this.orgs = res.data;
    });
    queryRoleSelect().then((res) => {
      this.roles = res.data;
    });
    this.loadData();
  },
  methods: {
    //#region 加载数据
    loadData() {
      this.readOnly =
        this.modifyEntity.operation === this.operationFlag.Detail
          ? true
          : false;
      this.form.resetFields(); // 重置参数值
      //修改，详情获取详细信息
      if (this.modifyEntity.operation !== this.operationFlag.Add) {
        let that = this;
        this.spinning = true;
        getAdminUser(this.modifyEntity.id )
          .then((res) => {
            that.entity = res.data;
            var setData = {};
            Object.keys(that.form.getFieldsValue()).forEach((item) => {
              setData[item] = that.entity[item];
            });

            if (that.entity.avatar) {
              that.fileList = [
                {
                  uid: "-1",
                  name: "image.png",
                  status: "done",
                  url: that.entity.avatar,
                },
              ];
            }
            // that.previewImage = that.entity.avatar;
            that.handleOrgChange(that.entity.defaultOrganizeId);
            that.handlePositionChange(that.entity.defaultPostationId);
            that.form.setFieldsValue(setData);
            that.spinning = false;
          })
          .catch((error) => {
            that.spinning = false;
          });
      }
    },
    //#endregion

    //#region 保存
    // 保存
    handleSubmit() {
      let that = this;
      this.spinning = true;
      this.form.validateFields((errors, values) => {
        if (!errors) {
          if (that.modifyEntity.operation === that.operationFlag.Add) {
            if (that.fileList.length > 0) {
              values.avatar = that.fileList[0].thumbUrl;
            }
            values.pwd = md5(values.pwd);
            addAdminUser(values).then((res) => {
              that.submitResult(res);
            });
          } else {
            that.entity = Object.assign(
              that.entity,
              that.form.getFieldsValue()
            );

            if (that.fileList.length > 0) {
              that.entity.avatar = that.fileList[0].thumbUrl;
            } else {
              that.entity.avatar = "";
            }
            updateAdminUser(that.entity).then((res) => {
              that.submitResult(res);
            });
          }
        } else {
          this.spinning = false;
        }
      });
    },
    // 保存结果
    submitResult(res) {
      if (res.code==200) {
        this.$notification.success({ description: res.msg });
        if (!this.hasClose) {
          this.$emit("handleRefresh");
        }
      } else {
        this.$notification.error({ description: res.msg });
      }
      this.spinning = false;
    },
    //#endregion

    //#region  取消、关闭、重置
    // 取消、关闭
    handleRefresh() {
      this.spinning = false;
      this.$emit("handleRefresh");
    },
    // 重置
    handleReset() {
      this.loadData();
    },
    //#endregion

    //#region 上传图片
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleImgChange(info) {
      if (this.fileList.length > 0) {
        let fileList = [...info.fileList];
        // 1. 限制上传文件数量
        //只显示最近上传的1个文件，旧文件将被新文件取代
        fileList = fileList.slice(-1);
        // 2. 从响应读取并显示文件链接
        fileList = fileList.map((file) => {
          if (file.response) {
            // 组件将显示文件。url链接
            file.url = file.response.url;
          }
          return file;
        });
        this.fileList = fileList;
      }
    },
    // 上传前对文件限制
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" ||
        file.type === "image/jpg" ||
        file.type === "image/png" ||
        file.type === "image/bmp";
      if (!isJpgOrPng) {
        this.$message.error("图片格式有误!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("图片大小最大为2MB!");
      }
      if (isLt2M && isJpgOrPng) {
        this.fileList = [...this.fileList, file];
      }
      return false;
    },
    // 上传后添加水印
    transformFile(file) {
      return new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          const canvas = document.createElement("canvas");
          const img = document.createElement("img");
          img.src = reader.result;
          img.onload = () => {
            const ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0);
            ctx.fillStyle = "red";
            ctx.textBaseline = "middle";
            ctx.fillText("DuLing", 20, 20);
            canvas.toBlob(resolve);
          };
        };
      });
    },
    //#endregion

    //#region 下拉设置值
    // 毕业院校
    handleEducationChange(val) {
      if (val) {
        this.form.setFieldsValue({ education: val });
      }
    },
    // 学位
    handleAcademicDegreeChange(val) {
      if (val) {
        this.form.setFieldsValue({ academicDegree: val });
      }
    },
    // 籍贯
    handleNationalityChange(val) {
      if (val) {
        this.form.setFieldsValue({ nationality: val });
      }
    },
    handleOrgChange(val) {
      this.positions = [];
      if (val) {
        this.form.setFieldsValue({ defaultOrganizeId: val });
        this.form.setFieldsValue({ defaultPostationId: "" });
        queryPositionSelect({ orgId: val }).then((res) => {
          this.positions = res.data;
        });
      }
    },
    handlePositionChange(val) {
      if (val) {
        this.form.setFieldsValue({ defaultPostationId: val });
      }
    },
    handleRoleChange(val) {
      if (val) {
        this.form.setFieldsValue({ roleId: val });
      }
    },
    //#endregion
  },
};
</script>
<style scoped>
.avatar-uploader>.ant-upload {
  width: 128px;
  height: 128px;
}

.avatar {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
